package com.coder520.mamabike.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coder520.mamabike.bo.UserBo;
import com.coder520.mamabike.common.Const;
import com.coder520.mamabike.common.Parameter;
import com.coder520.mamabike.common.ResponseCode;
import com.coder520.mamabike.common.ServerResponse;
import com.coder520.mamabike.common.exception.MyException;
import com.coder520.mamabike.dao.UserMapper;
import com.coder520.mamabike.dao.cache.RedisDao;
import com.coder520.mamabike.jms.SMSProcessor;
import com.coder520.mamabike.pojo.LoginInfo;
import com.coder520.mamabike.pojo.User;
import com.coder520.mamabike.security.AESUtil;
import com.coder520.mamabike.security.Base64Utils;
import com.coder520.mamabike.security.MD5Util;
import com.coder520.mamabike.security.RSAUtil;
import com.coder520.mamabike.service.IUserService;
import com.coder520.mamabike.utils.QiNiuUpLoadUtil;
import com.coder520.mamabike.utils.RandomUtil;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes;

/**
 * Created by ASUS on 2017/8/12.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private Parameter parameter;

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SMSProcessor smsProcessor;

    public ServerResponse login(LoginInfo loginInfo) {

        if (loginInfo != null) {
            String token;

            String data = loginInfo.getData();
            String key = loginInfo.getKey();
            if (StringUtils.isNotBlank(data) && StringUtils.isNotBlank(key)) {
                try {
                    /**解密数据*/
                    String result = deCrept(data, key);
                    JSONObject jsonObject = JSON.parseObject(result);

                    String mobile = jsonObject.getString("mobile");
                    String code = jsonObject.getString("code");
                    if (StringUtils.isNotBlank(mobile) && StringUtils.isNotBlank(code)) {
                        String cache_code = redisDao.getCache(mobile);
                        if (StringUtils.isNotBlank(cache_code) && StringUtils.equals(cache_code, code)) {
                            User user = userMapper.selectByMobile(mobile);
                            /**用户不存在    进行注册*/
                            if (user == null) {
                                user.setMobile(Long.parseLong(mobile));
                                user.setNickname(mobile);
                                userMapper.insert(user);
                            }
                            /**生成Token*/
                            token = generateToken(user);

                            UserBo userBo = new UserBo();
                            userBo.setMobile(user.getMobile());
                            userBo.setUserId(user.getId());
                            userBo.setToken(token);

                            /**缓存token*/
                            redisDao.cacheObject(userBo);
                            return ServerResponse.createBySuccess(userBo);
                        }
                        return ServerResponse.createByError("验证码错误");
                    }
                } catch (Exception e) {
                    return ServerResponse.createByError("数据解析错误");
                }
            }
        }
        return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
    }


    public ServerResponse updateNickName(User user) {
        if (user != null && user.getNickname() != null) {
            int rowResult = userMapper.updateByPrimaryKeySelective(user);
            if (rowResult > 0) {
                return ServerResponse.createBySuccess("修改昵称成功");
            }
        }
        return ServerResponse.createByError("修改昵称失败");
    }

    public ServerResponse sendSMS(String phone, String ip) {
        int code = RandomUtil.getRandomNumber();
        Integer state = redisDao.checkSMS(phone, code, Const.SMSType.REGIST, 60, ip);
        /**校验未通过*/
        if (state != Const.SMSStatus.SUCCESS.getCode()) {
            return ServerResponse.createByError(Const.SMSStatus.codeOf(state).getDesc());
        }
        Destination destination = new ActiveMQQueue(Const.Queue.SMS_QUEUE);
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        params.put("tepId", "60203730");
        params.put("code", String.valueOf(code));
        String result = JSON.toJSONString(params);
        /**发送短信入队*/
        smsProcessor.sendSmsToQueue(destination, result);
        return ServerResponse.createBySuccess("发送成功");
    }

    /**
     * 上传图片到云存储
     * @param file
     * @param user
     * @return
     */
    public ServerResponse updateHeadImg(MultipartFile file, User user) {
        if (file == null) {
            return ServerResponse.createByError("参数错误");
        }
        String result = null;
        try {
            result = QiNiuUpLoadUtil.uploadImg(file);
        } catch (IOException e) {
            logger.error("上传图片失败", e);
            return ServerResponse.createByError("上传图片失败");
        }
        user.setHeadImg(parameter.getPreff() + result);

        int rowResult = userMapper.updateByPrimaryKeySelective(user);
        if (rowResult == 0) {
            return ServerResponse.createByError("上传图片失败");
        }
        return ServerResponse.createBySuccess(result);
    }

    /**
     * 生成token
     *
     * @param user
     * @return
     */
    private String generateToken(User user) {
        String token = user.getId() + user.getMobile() + ":" + System.currentTimeMillis();
        return MD5Util.getMD5(token);
    }

    /**
     * 解析客户端加密信息
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    private String deCrept(String data, String key) throws Exception {
        byte[] deBys = RSAUtil.decrypt(Base64Utils.decode(key));
        String deKey = new String(deBys, "utf-8");
        String result = AESUtil.decrypt(data, deKey);
        return result;
    }


}
